package com.cloudz.iptv.fragment.content.v1;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.TypedValue;
import android.view.View;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudz.iptv.R;
import com.cloudz.iptv.api.v1.BingServiceApi;
import com.cloudz.iptv.fragment.BaseFragment;
import com.cloudz.iptv.fragment.content.v1.adapter.LiveChannlAdapter;
import com.cloudz.iptv.fragment.content.v1.adapter.data.ItemLiveChannel;
import com.cloudz.iptv.player.PlayerLiveActivity;
import com.cloudz.iptv.player.base.DataInter;
import com.cloudz.iptv.player.base.ReceiverGroupManager;
import com.cloudz.iptv.utils.InPutJson;
import com.cloudz.iptv.utils.ResponseUtils;
import com.cloudz.iptv.utils.RetrofitUtils;
import com.cloudz.iptv.utils.SimplePreference;
import com.cloudz.iptv.utils.banner.GlideImageLoader;
import com.cloudz.iptv.utils.cache.ACache;
import com.cloudz.iptv.utils.cache.ACacheConstants;
import com.kk.taurus.playerbase.entity.DataSource;
import com.kk.taurus.playerbase.player.IPlayer;
import com.kk.taurus.playerbase.receiver.ReceiverGroup;
import com.kk.taurus.playerbase.widget.BaseVideoView;
import com.owen.tvrecyclerview.widget.TvRecyclerView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Page2 extends BaseFragment
{
    private boolean isDestroyed = false;

    @BindView(R.id.videoView)
    BaseVideoView videoView;

    @BindView(R.id.live_channel)
    TvRecyclerView tvRecyclerViewLiveChannel;

    /**
     * 当前选中url
     */
    private String currentUrl;

    /**
     * 轮播图
     */
    @BindView(R.id.banner)
    Banner banner;

    private View view;

    private ACache aCache;

    private ReceiverGroup mReceiverGroup;

    // 是否开始
    private boolean hasStart;

    // 快速点击间隔
    private static final int FAST_CLICK_DELAY_TIME = 5000;

    private static long lastClickTime;

    Handler handler;

    /**
     * 第一次进入
     */
    private boolean status = true;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);

        this.view = view;

        aCache = ACache.get(view.getContext());

        this.handler = new Handler();

        // 初始化轮播图
        initBanner();

        // 初始化播放器
        initPlayer();

        addListener();

        addAdpater();
    }

    @Override
    public int getLayoutId()
    {
        return R.layout.activity_pager_2;
    }

    /**
     * 初始化轮播图
     */
    public void initBanner()
    {

        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());

        JSONArray adImage = aCache.getAsJSONArray(ACacheConstants.AD_IMAGE_CACHE);

        if (adImage != null && !adImage.isEmpty())
        {
            //设置图片集合
            banner.setImages(adImage.toJavaList(String.class));
        }

        //设置轮播时间
        banner.setDelayTime(3000);

        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);

        //banner设置方法全部调用完毕时最后调用
        banner.start();

    }

    /**
     * 播放视频
     */
    public void initPlayer()
    {

        if (!hasStart)
        {

            // 组装组件
            mReceiverGroup = ReceiverGroupManager.get().getReceiverGroup(this.getActivity());

            mReceiverGroup.getGroupValue().putBoolean(DataInter.Key.KEY_CONTROLLER_TOP_ENABLE, true);

            videoView.setReceiverGroup(mReceiverGroup);

//            videoView.setRenderType(1);


            this.hasStart = true;
        }


    }

    boolean flg = false;

    /**
     * 添加监听
     */
    void addListener()
    {

        tvRecyclerViewLiveChannel.setOnItemListener(new TvRecyclerView.OnItemListener()
        {
            // 上次选中
            @Override
            public void onItemPreSelected(TvRecyclerView parent, View itemView, int position)
            {

            }

            // 当前选中
            @Override
            public void onItemSelected(TvRecyclerView parent, View itemView, int position)
            {
                onMoveFocusBorder(itemView, 1.1f);

                LiveChannlAdapter adapter = (LiveChannlAdapter) parent.getAdapter();

                ItemLiveChannel itemLiveChannel = (ItemLiveChannel) adapter.getItem(position);

                String url = itemLiveChannel.url;


                if (position > 0)
                {
                    flg = true;
                }

                if (url != null && flg)
                {
                    if (StringUtils.isNotBlank(currentUrl) && !currentUrl.equals(url))
                    {

//                        if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME)
//                        {
//                            return;
//                        }
//                        lastClickTime = System.currentTimeMillis();

                        videoView.stop();

                        currentUrl = url;

                        handler.removeCallbacksAndMessages(null);

                        handler.postDelayed(()->{

                            replay();

                        }, 1000);

                    }

                }
            }

            // 点击
            @Override
            public void onItemClick(TvRecyclerView parent, View itemView, int position)
            {
                LiveChannlAdapter adapter = (LiveChannlAdapter) parent.getAdapter();

                ItemLiveChannel itemLiveChannel = (ItemLiveChannel) adapter.getItem(position);
                String url = itemLiveChannel.url;
                if (url != null)
                {
                    Intent intent = new Intent(getActivity(), PlayerLiveActivity.class);
                    intent.putExtra("url", url);
                    intent.putExtra("adapter", (Serializable) adapter.getDatas());
                    intent.putExtra("position", position);

                    intent.putExtra("title", itemLiveChannel.title);

                    intent.putExtra("no", itemLiveChannel.no);

                    startActivity(intent);


                } else
                {
                    showToast("播放地址不存在");
                }

            }
        });

        // 离开底部菜单
        tvRecyclerViewLiveChannel.setOnFocusChangeListener(new View.OnFocusChangeListener()
        {
            @Override
            public void onFocusChange(View view, boolean b)
            {
//                if (!b)
//                {
//                    focusBorder.setVisible(false);
//                } else {
//                    focusBorder.setVisible(true);
//                }
                focusBorder.setVisible(true);
            }
        });
    }

    /**
     * 添加适配器
     */
    void addAdpater()
    {
        //设置布局横纵间隙
        tvRecyclerViewLiveChannel.setSpacingWithMargins((int) dp2px(0), (int) dp2px(0));

        JSONArray channels = aCache.getAsJSONArray(ACacheConstants.CHANNEL_CACHE);
        if (channels != null)
        {
            setAdapter(channels);
        } else
        {
            getChannelData();
        }

        //选中居中, 与上面的偏移量二选一
        tvRecyclerViewLiveChannel.setSelectedItemAtCentered(true);

        //加载更多监听
        tvRecyclerViewLiveChannel.setOnLoadMoreListener(new TvRecyclerView.OnLoadMoreListener()
        {
            @Override
            public boolean onLoadMore()
            {
                tvRecyclerViewLiveChannel.setLoadingMore(true); //正在加载数据
//                adapter.appendDatas(); //加载数据
                tvRecyclerViewLiveChannel.setLoadingMore(false); //加载数据完毕
                return true; //是否还有更多数据
            }
        });

    }

    /**
     * 获取频道
     */
    private void getChannelData()
    {


        // 验证绑定情况
        BingServiceApi bingServiceApi = RetrofitUtils.getInstance().createApi(SimplePreference.getServerUrl(this.view.getContext()), BingServiceApi.class);

        bingServiceApi.getIpTvChannel(0, 100).enqueue(new Callback<ResponseBody>()
        {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response)
            {

                int code = response.code();
                if (code == 200)
                {
                    try
                    {
                        InPutJson inOutJson = ResponseUtils.getInOutJson(response);

                        if (inOutJson.result)
                        {
                            JSONObject data = inOutJson.getJSONObject();
                            JSONArray channels = data.getJSONArray("rows");

                            aCache.put(ACacheConstants.CHANNEL_CACHE, channels, ACacheConstants.CACHE_TIME * ACache.TIME_DAY);

                            setAdapter(channels);

                            status = false;

                        }
                    } catch (Exception e)
                    {
                        e.printStackTrace();
                    }

                } else
                {
                    showToast("重试失败");
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t)
            {
                showToast("重试失败");
            }
        });
    }

    /**
     * 设置缓存
     *
     * @param channels
     */
    public void setAdapter(JSONArray channels)
    {

        List<ItemLiveChannel> itemMenuFooters = new ArrayList<>();

        for (int i = 0, size = channels.size(); i < size; i++)
        {
            JSONObject channel = channels.getJSONObject(i);

            String url = channel.getString("channelUrl");

            // 设置第一个视频
            if (i == 0 && status)
            {

                currentUrl = url;

                replay();

            }

            ItemLiveChannel itemLiveChannel = new ItemLiveChannel(String.format("%03d", i + 1), channel.getString("channelName"), channel.getString("channelIcon"), url);

            itemMenuFooters.add(itemLiveChannel);
        }

        LiveChannlAdapter adapter = new LiveChannlAdapter(getContext(), itemMenuFooters);

        tvRecyclerViewLiveChannel.setAdapter(adapter);
    }

    private float dp2px(int dp)
    {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }

    /**
     * 重播
     */
    private void replay()
    {
        videoView.stop();

        DataSource dataSource = new DataSource(currentUrl);

        videoView.setDataSource(dataSource);


        videoView.start();

    }

    @Override
    public void onStart()
    {
        super.onStart();
        //开始轮播
        banner.startAutoPlay();
    }

    @Override
    public void onStop()
    {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
    }

    @Override
    public void onPause()
    {
        super.onPause();

        int state = videoView.getState();
        if (state == IPlayer.STATE_PLAYBACK_COMPLETE)
            return;
//        if (videoView.isInPlaybackState())
//        {
//            videoView.pause();
//        } else
//        {
//            videoView.stop();
//        }


        videoView.stop();
    }

    @Override
    public void onResume()
    {
        super.onResume();

        int state = videoView.getState();
        if (state == IPlayer.STATE_PLAYBACK_COMPLETE)
            return;
//        if (videoView.isInPlaybackState())
//        {
//            videoView.resume();
//        } else
//        {
//            videoView.rePlay(0);
//        }
//        initPlayer();


        replay();

    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        videoView.stopPlayback();
    }

    @Override
    public void onHiddenChanged(boolean hidden)
    {
        super.onHiddenChanged(hidden);

        if (hidden)
        {
            //Fragment隐藏时调用
            // 暂停
            videoView.stop();
        } else
        {
            //Fragment显示时调用
            replay();
        }
    }
}
